import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import '../models/chat_message.dart';

class MessageFavoriteProvider with ChangeNotifier {
  static const String _favoritesKey = 'favorite_messages';
  final SharedPreferences _prefs;
  List<Map<String, dynamic>> _favorites = [];

  MessageFavoriteProvider(this._prefs) {
    _loadFavorites();
  }

  Future<void> _loadFavorites() async {
    final favorites = _prefs.getStringList(_favoritesKey) ?? [];
    _favorites = favorites.map((m) => jsonDecode(m) as Map<String, dynamic>).toList();
    notifyListeners();
  }

  Future<void> toggleFavorite(ChatMessage message) async {
    final messageJson = {
      'characterName': message.characterName,
      'text': message.text,
      'timestamp': message.timestamp.toIso8601String(),
    };

    if (_favorites.any((m) => m['timestamp'] == message.timestamp.toIso8601String())) {
      _favorites.removeWhere((m) => m['timestamp'] == message.timestamp.toIso8601String());
    } else {
      _favorites.add(messageJson);
    }

    await _prefs.setStringList(_favoritesKey, _favorites.map((m) => jsonEncode(m)).toList());
    notifyListeners();
  }

  bool isFavorite(ChatMessage message) {
    return _favorites.any((m) => m['timestamp'] == message.timestamp.toIso8601String());
  }

  void addFavorite(Map<String, dynamic> message) {
    final favorites = _prefs.getStringList('favorites') ?? [];
    favorites.add(jsonEncode(message));
    _prefs.setStringList('favorites', favorites);
    notifyListeners();
  }

  void removeFavorite(String timestamp) {
    final favorites = _prefs.getStringList(_favoritesKey) ?? [];
    favorites.removeWhere((item) {
      final message = jsonDecode(item);
      return message['timestamp'] == timestamp;
    });
    _prefs.setStringList(_favoritesKey, favorites);
    _favorites = favorites.map((m) => jsonDecode(m) as Map<String, dynamic>).toList();
    notifyListeners();
  }

  List<Map<String, dynamic>> get favorites => _favorites;
} 